<template>
	<view class="content" style="background-color: #F4F4F4;height: 100vh;">
		<tn-nav-bar bgClass="bg-gradual-blue">
			<view @click="showPasswordFun('NAME')">
				{{ bleName }}
			</view>
		</tn-nav-bar>

		<view :style="{paddingTop: vuex_custom_bar_height + 'px'}">
			<view class="margin tn-flex tn-flex-row-center">
				<zu-battery :showPercent='true' :battery="readValue.RSOC" height='120rpx' width="300rpx"
					@click="showPasswordFun('CONFIG')"></zu-battery>
			</view>



			<view class="margin-top-lg">
				<tn-grid col="2" align="center">
					<tn-grid-item backgroundColor='#F4F4F4'>
						<view class="task-item b-card ">
							<view class="b-flex-space">
								<view class="task-item-describe">
									<view class="title b-fontw">
										电压
									</view>
									<view class="text">
										{{ readValue.Voltage }}
										<text class="text-lg" style="padding-left: 6rpx;">V</text>
									</view>
								</view>
								<image class="task-item-icon" src="/static/img/ble/dy.png" mode="">
								</image>
							</view>
						</view>
					</tn-grid-item>

					<tn-grid-item backgroundColor='#F4F4F4'>
						<view class="task-item b-card ">
							<view class="b-flex-space">
								<view class="task-item-describe">
									<view class="title b-fontw">
										电流
									</view>
									<view class="text">
										{{ readValue.CurCadc?readValue.CurCadc: 0 }}
										<text class="text-lg" style="padding-left: 6rpx;">A</text>
									</view>
								</view>
								<image class="task-item-icon" src="/static/img/ble/dl.png" mode="">
								</image>
							</view>
						</view>
					</tn-grid-item>
					<tn-grid-item backgroundColor='#F4F4F4'>
						<view class="task-item b-card ">
							<view class="b-flex-space">
								<view class="task-item-describe">
									<view class="title b-fontw">
										最高温度
									</view>
									<view class="text">
										{{readValue.Tmax}}
										<text class="text-lg" style="padding-left: 6rpx;">℃</text>
									</view>
								</view>
								<image class="task-item-icon" src="/static/img/ble/wd.png" mode="">
								</image>
							</view>
						</view>
					</tn-grid-item>
					<tn-grid-item backgroundColor='#F4F4F4'>
						<view class="task-item b-card ">
							<view class="b-flex-space">
								<view class="task-item-describe">
									<view class="title b-fontw">
										最低温度
									</view>
									<view class="text">
										{{readValue.Tmin}}
										<text class="text-lg" style="padding-left: 6rpx;">℃</text>
									</view>
								</view>
								<image class="task-item-icon" src="/static/img/ble/wd.png" mode="">
								</image>
							</view>
						</view>
					</tn-grid-item>
				</tn-grid>
			</view>


			<view class="margin">
				<view class="tn-margin-top-sm">
					<tn-list-cell :radius="true">
						<view class="list-icon-text">
							<view class="list__left">
								<view class="list__left__text">
									<text class="text-lg text-bold padding-left-sm">充电开关状态</text>
								</view>
							</view>
							<view class="list__right">
								<tn-switch activeColor="#409eff" @change='e => setMos(e, "charge")'
									:value="readValue['PackStatus'][2]*1===1?true:false"></tn-switch>
							</view>
						</view>
					</tn-list-cell>
				</view>

				<view class="tn-margin-top-sm">
					<tn-list-cell :radius="true">
						<view class="list-icon-text">
							<view class="list__left">
								<view class="list__left__text">
									<text class="text-lg text-bold padding-left-sm">放电开关状态</text>
								</view>
							</view>
							<view class="list__right">
								<tn-switch activeColor="#409eff" @change='e => setMos(e, "charge")'
									:value="readValue['PackStatus'][1]*1===1?true:false"></tn-switch>
							</view>
						</view>
					</tn-list-cell>
				</view>

			</view>


			<view class="margin bg-white shadow-lg radius-25">
				<demo-title title="电芯电压">
					<tn-grid col="4" align="around">
						<tn-grid-item v-for="(item,index) in readValue['Cell_Num']*1" :key="index">
							<view style="width: 100%;display: flex; justify-content: center;">
								<view class="margin-tb-sm"
									:class='readValue["VCell"+(item+1)]*1===readValue["Vmax"]*1?"bg-img-dc-max":readValue["VCell"+(item+1)]*1===readValue["Vmin"]*1?"bg-img-dc-min":"bg-img-dc"'>
									<view
										style="display: flex; justify-content: space-around;align-items: center;flex-direction: column;width: 100%;height: 100%;padding: 5px;">
										<view class="text-bold">{{readValue['VCell'+(item+1)]}}mV</view>
										<view class="text-sm">电芯 {{item+1}}</view>
									</view>
								</view>
							</view>
						</tn-grid-item>
					</tn-grid>
				</demo-title>
			</view>
		</view>
		<view style="height: 10vh;"></view>

		<!-- 修改蓝牙名称弹窗 -->
		<template v-if="showDialog">
			<tn-modal :value="showDialog" @click="reName" @cancel="onDialogClose" custom :button="buttons"
				padding='30rpx'>
				<view class="custom-modal-content">
					<tn-form :labelWidth="140" style="width: 100%;">
						<tn-form-item label="蓝牙名称: " :borderBottom="false">
							<tn-input v-model="dialogInput" border :placeholder="bleName"></tn-input>
						</tn-form-item>
					</tn-form>
				</view>
			</tn-modal>
		</template>

		<!-- 密码弹窗 -->
		<template v-if="showPassword">
			<tn-modal :value="showPassword" @click="e=>onDialogClick(e,'CHECK')" @cancel="onDialogClose" custom
				:button="buttons" padding='30rpx'>
				<view class="custom-modal-content">
					<tn-form :labelWidth="80" style="width: 100%;">
						<tn-form-item label="密码:" :borderBottom="false">
							<tn-input v-model="dialogInput" border></tn-input>
						</tn-form-item>
					</tn-form>
				</view>
			</tn-modal>
		</template>

	</view>
</template>

<script>
	import {
		getProfile
	} from '@/api/modules/common.js'
	import {
		getToken
	} from "@/common/storage/auth.js"



	import BLE from "@/libs/bluetooth/BLE.js";
	import Protocol from "@/libs/protocol/anxuan/protocol.js";
	import bleData from "@/libs/protocol/anxuan/bleData.js";
	import demoTitle from '../components/demo-title.vue'
	import zuBattery from '../components/zu-battery/zu-battery.vue'

	let timer = null
	let sendTimer = null
	export default {
		components: {
			demoTitle,
			zuBattery
		},
		data() {
			return {
				readList: bleData.writeList,
				readAllParams: bleData.readAndWrite,
				writeValue: bleData.writeValue,
				bleName: null,
				dialogInput: '',
				dialogType: '',
				showPasswordCount: '',
				showPassword: false,
				messageId: '',
				readValue: {},
				userLevels: [],
				deviceInfo: {},
				isWrite: false,
				showLogin: false,
				sendEnable: false,
				readIndex: 0,
				allCount: 0,
				buttons: [{
						text: '取消',
						backgroundColor: '#AAAAAA',
						fontColor: '#FFFFFF'
					},
					{
						text: '确定',
						backgroundColor: '#01BEFF',
						fontColor: '#FFFFFF'
					}
				]
			}
		},
		onLoad(options) {
			// 保持屏幕常亮
			uni.setKeepScreenOn({
				keepScreenOn: true
			});
			if (options.name) {
				this.bleName = options.name
			}
			var that = this;
			that.isWrite = false;
			that.readIndex = 0;
		},
		onShow() {
			if (!getApp().globalData.bleObj.state) {
				BLE.Connect(getApp().globalData.bleObj.deviceId, () => {})
			}
			let that = this
			that.readAllParams.map(t => {
				that.readValue[t.name] = ''
			})

			if (sendTimer != null) {
				clearInterval(sendTimer)
				sendTimer = null;
			}
			if (timer != null) {
				clearInterval(timer)
				timer = null;
			}

			//设置值更改函数
			that.SetValueChanged();
			var state = getApp().globalData.bleObj.state;
			var isNotify = getApp().globalData.bleObj.isNotify;
			this.isWrite = false
			that.sendFirstToBle()
			//定时读取蓝牙数据
			timer = setInterval(() => {
				that.sendFirstToBle()
				that.showPasswordCount = 0
			}, 2000)

			//定时发送数据到服务器
			sendTimer = setInterval(() => {
				that.sendDataToMqtt()
			}, 1000)

			const deviceId = that.bleName ? that.bleName : getApp().globalData.bleObj.name;
			console.log('deviceId', deviceId);
			this.getMqttInfo(deviceId)
			// 获取用户等级密码信息
			this.$api.common.listUserLevel().then(res => {
				this.userLevels = {}
				if (res.code === 200) {
					for (var i = 0; i < res.data.length; i++) {
						let t = res.data[i]
						this.userLevels['level.' + t.configKey.split('level.')[1]] = t.configValue
					}
				}
				console.log('this.userLevels', this.userLevels);
			})
		},
		onHide() {
			if (sendTimer != null) {
				clearInterval(sendTimer)
				sendTimer = null;
			}
			if (timer != null) {
				clearInterval(timer)
				timer = null;
			}
			this.isWrite = false
			// if (getApp().globalData.bleObj.state) {
			// 	BLE.Close()
			// }
			this.endMqtt()
		},
		onUnload() {
			if (sendTimer != null) {
				clearInterval(sendTimer)
				sendTimer = null;
			}
			if (timer != null) {
				clearInterval(timer)
				timer = null;
			}
			// if (getApp().globalData.bleObj.state) {
			// 	BLE.Close()
			// }
			this.endMqtt()
		},
		methods: {
			/**
			 * 连续点击标题或者 电池容量
			 * @param {Object} flag
			 */
			showPasswordFun(flag) {
				let count = this.showPasswordCount++
				if (count > 2 && flag === 'NAME') {
					//弹窗修改蓝牙名称
					this.showPassword = true
					this.dialogType = 'NAME'
				}
				if (count > 5 && flag === 'CONFIG') {
					//弹窗修改参数
					this.showPassword = true
					this.dialogType = 'CONFIG'
				}
			},
			/**
			 * 
			 */
			onDialogClose() {
				this.showDialog = false;
				this.dialogInput = null
			},
			/**
			 * 
			 */
			onDialogClick(e, type) {
				let that = this
				let input = that.dialogInput
				console.log(that.dialogInput);
				if (e.index < 1) {
					that.showPassword = false;
					that.showDialog = false;
					that.dialogInput = ''
					return
				}
				if (type === 'CHECK') {
					that.showPassword = false
					// 判断密码
					if (that.dialogType === 'NAME' && input === that.userLevels['level.1']) {
						that.showDialog = true
						that.dialogInput = ''
						return
					}
					if (that.dialogType === 'CONFIG' && input === that.userLevels['level.2']) {
						that.dialogInput = ''
						uni.navigateTo({
							url: '/pages_ble/ble/anxuan/config?n=' + that.bleName
						})
					}
					that.showDialog = false

				} else {
					// 修改蓝牙名称
					if (that.dialogType === 'NAME') {

					}
				}
			},
			sendDataToMqtt() {
				let that = this
				var state = getApp().globalData.bleObj.state;
				if (that.sendEnable && state) {
					let messages = []
					for (let key in that.readValue) {
						messages.push({
							id: key,
							//value: 0,
							value: Array.isArray(this.readValue[key]) ? 0 : this.readValue[key],
							remark: ''
						})
					}
					that.$mqttTool.publish(
						`/${that.deviceInfo.productId}/${that.deviceInfo.serialNumber}/property/post`,
						JSON.stringify(messages), 'name')
				}
			},
			sendFirstToBle() {
				let that = this
				var state = getApp().globalData.bleObj.state;
				var deviceId = getApp().globalData.bleObj.deviceId;
				var isWrite = that.isWrite;
				if (state && deviceId != '' && isWrite === false) {
					that.readIndex = 0;
					that.isWrite = true;
					Protocol.writeToRead('1000', '0007', function(res) {
						console.log('sendFirstToBle');
					});
				}
			},
			//设置蓝牙请求数据
			SetValueChanged() {
				var that = this;
				//处理数据
				BLE.bleCallBack.CharacteristicValueChange = async function(res) {
					if (res != undefined && res != null && res != '') {
						var current = that.readList[that.readIndex];
						var packages = Protocol.solutionData(res, current.len);
						if (packages) {
							if (packages.command == '03') {
								let items = await loadData(that.readAllParams, packages, current.start, that);
								that.readAllParams = JSON.parse(JSON.stringify(items))
								that.readIndex = that.readIndex + 1;
								if (that.readIndex >= that.readList.length) {
									that.readIndex = 0;
								}
								Protocol.writeToRead(that.readList[that.readIndex].start,
									'000' + that.readList[that.readIndex].len, () => {
										that.isWrite = true
									});
							} else {
								that.isWrite = false
								console.log('packages', packages);
							}
						} else {
							that.isWrite = false
						}
					}
				}
			},
			/**
			 * 获取MQTT连接信息
			 */
			getMqttInfo(deviceId) {
				let that = this;
				let productCode = getApp().globalData.bleVersion
				that.$api.device.getMqttInfo(deviceId,productCode).then(res => {
					if (!res.data || !res.data.device) {
						return
					}
					let device = res.data.device
					let mqttInfo = res.data.mqttInfo
					let info = {
						clientId: mqttInfo.clientId,
						username: mqttInfo.username,
						password: mqttInfo.passwd,
					}
					setTimeout(async () => {
						await this.connectMqtt(info)
						this.mqttSubscribe(device);
						this.mqttCallback();
					}, 100)
				})
			},
			async mqttSendOk(messages) {
				let that = this
				that.$mqttTool.publish(
					`/${that.deviceInfo.productId}/${that.deviceInfo.serialNumber}/property/post`,
					JSON.stringify(messages), '')
			},
			/* 断开Mqtt消息服务器 */
			async endMqtt() {
				await this.$mqttTool.end();
				this.sendEnable = false
			},
			/* 连接Mqtt消息服务器 */
			async connectMqtt(info) {
				let that = this
				if (this.$mqttTool.client === null) {
					if (info && info.username) {
						await this.$mqttTool.connect(info);
						this.$mqttTool.client.on('connect', function(res) {});
					}
				}
			},
			/* Mqtt回调处理  */
			mqttCallback() {
				let that = this
				let topicArrs = [
					'/function/get',
					'/monitor/get'
				]
				this.$mqttTool.client.on('message', async (topic, message, buffer) => {
					console.log('message:', message.toString());
					console.log('topic:', topic);
					message = JSON.parse(message.toString());
					if (!message) {
						return;
					};
					if (topic.includes(topicArrs[1])) {
						if (message.count * 1 > 0) {
							that.sendEnable = true
							setTimeout(() => {
								that.sendEnable = false
							}, message.count * 1000)
						} else {
							that.sendEnable = false
						}
						let MAC = getApp().globalData.bleObj.MAC
						utils.readListWithFilterExpire(MAC + "PROTECT").then(saveArr => {
							console.log('saveArr', saveArr);
							// 发送后台
							for (var i = 0; i < saveArr.length; i++) {
								let t = saveArr[i];
								t['productId'] = productId
								t['alertLevel'] = 3
								t['status'] = 1
								t['detail'] = ''
								saveAlertLog(t).then(res => {
									console.log('上传成功', res);
								})
							}
						})
					}

					if (topic.includes(topicArrs[0])) {
						for (var i = 0; i < message.length; i++) {
							let item = message[i]
							console.log(item);
							let address = that.writeValue[item.id]
							let v = parseFloat(item.value);
							if (!isNaN(v)) {
								console.log('v', v);
								Protocol.writeToWrite(address, Protocol.encryption(address, v), async () => {
									console.log('发送指令成功');
									await that.mqttSendOk([item])
								})
							}
						}
					}

				});
			},
			/** Mqtt订阅主题 */
			mqttSubscribe(device) {
				// 订阅当前设备状态和实时监测
				let topics = buildTopics(device);
				this.$mqttTool.subscribe(topics);
			},
		}
	}


	/**
	 * 解析数据
	 * @param {Object} readData
	 * @param {Object} packages
	 * @param {Object} address
	 */
	async function loadData(items, packages, address, that) {
		var j = 0;
		var length = packages.length * 0.5;
		for (var i = 0; i < items.length; i++) {
			if (items[i].address == address) {
				j = i;
				break;
			}
		}
		for (var i = 0; i < length; i++) {
			var v = packages.data.substr((i * 4), 4);
			var t = items[(j + i)];
			var value = Protocol.algorithm(t.address, v);
			if (t.address === '1014') { //总压欠压保护电压值
				let v = getPROTECT(value)
				let MAC = getApp().globalData.bleObj.MAC
				let saveArr = await that.$util.readListWithFilterExpire(MAC + "PROTECT")
				for (var m = 0; m < v.length; m++) {
					let n = v[m]
					if (n.value > 0) {
						let it = {
							serialNumber: MAC,
							createTime: that.$util.parseTime(new Date()),
							alertName: n.name
						}
						saveArr.push(it)
						if (saveArr.length > 5) {
							saveArr.splice(0, 1)
						}
					}
				}
				that.$util.saveListWithExpire(MAC + "PROTECT", saveArr, 172800)
			}
			t.value = value;
			that.readValue[t.name] = t.value ? t.value : ''
		}
		return items;
	}


	function getPROTECT(binaryData) {
		const bitInfo = [{
				name: '短路保护',
				value: binaryData[0]
			},
			{
				name: '压差保护',
				value: binaryData[1]
			},
			{
				name: '放电二级过流',
				value: binaryData[2]
			},
			{
				name: '充电过流',
				value: binaryData[3]
			},
			{
				name: '放电过流',
				value: binaryData[4]
			},
			{
				name: '总压过压',
				value: binaryData[5]
			},
			{
				name: '总压欠压',
				value: binaryData[6]
			},
			{
				name: '单体过压',
				value: binaryData[7]
			},
			{
				name: '单体欠压',
				value: binaryData[8]
			},
			{
				name: '充电高温保护',
				value: binaryData[9]
			},
			{
				name: '充电低温保护',
				value: binaryData[10]
			},
			{
				name: '放电高温保护',
				value: binaryData[11]
			},
			{
				name: '放电低温保护',
				value: binaryData[13]
			}
		];
		return bitInfo;
	}

	/**
	 * MQTT主题订阅配置
	 * @param {Object} device 设备信息
	 */
	function buildTopics(device) {
		let topics = [];
		let preUrl = '/' + device.productId + '/' + device.serialNumber;
		// 订阅当前设备状态和实时监测
		let functionGet = preUrl + '/function/get';
		let topicInfo = preUrl + '/info/get';
		let topicMonitor = preUrl + '/monitor/get';
		topics.push(functionGet);
		topics.push(topicInfo);
		topics.push(topicMonitor);
		return topics
	}
</script>


<style scoped lang="scss">
	.radius-25 {
		border-radius: 25rpx;
	}

	.b-card {
		margin: 26rpx 32rpx;
		padding: 25rpx;
		background-color: #FFFFFF;
		border-radius: 18rpx;
		box-shadow: 12rpx 12rpx 10rpx #a7a7a7;
	}

	.b-flex-space {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.b-fontw {
		font-weight: 600;
	}


	.task-item {

		.task-item-icon {
			width: 80rpx;
			height: 80rpx;
		}

		.task-item-describe {
			height: 100rpx;
			width: 150rpx;
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			margin-right: 30rpx;

			.title {
				font-size: 24rpx;
			}

			.text {
				margin-top: 20rpx;
				font-size: 46rpx;
			}
		}
	}

	.bg-img-dc-max {
		background-image: url('/static/img/ble/dx-max.png');
		background-size: 100% 100%;
		color: #13227a;
		height: 90rpx;
		width: 86px;
	}

	.bg-img-dc-min {
		background-image: url('/static/img/ble/dx-min.png');
		background-size: 100% 100%;
		height: 90rpx;
		color: #0b988f;
		width: 86px;
	}

	.bg-img-dc {
		background-image: url('/static/img/ble/dx.png');
		background-size: 100% 100%;
		height: 90rpx;
		width: 86px;
		color: #1296db;
	}



	.list__options {
		display: flex;
		align-items: center;
		justify-content: space-evenly;
	}

	.list {
		&__left {
			display: flex;
			align-items: center;
			justify-content: flex-start;

			&__icon,
			&__image {
				margin-right: 18rpx;
			}
		}

		&__right {
			display: flex;
			align-items: center;
			justify-content: flex-end;
		}
	}

	.list-icon-text,
	.list-image-text {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.list-image-text {
		.list {
			&__left {
				&__image {
					width: 20rpx;
					height: 20rpx;
				}
			}
		}
	}
</style>